const Service = require('egg').Service;
const { OpenAI } = require('openai');

class OpenAIService extends Service {
  constructor(ctx) {
    super(ctx);
    this.client = new OpenAI({
      apiKey: this.config.openai302.apiKey,
      timeout: 60000, // 60 seconds timeout
      maxRetries: 2, // Maximum number of retries
    });
  }

  async chatCompletion(messages) {
    const startTime = Date.now();
    try {
      const response = await this.client.chat.completions.create({
        model: this.config.openai302.model || 'gpt-3.5-turbo',
        messages,
        stream: true,
        max_tokens: this.config.openai302.maxTokens,
        temperature: this.config.openai302.temperature,
      });

      const duration = Date.now() - startTime;
      this.ctx.logger.info('[OpenAI] Request completed', {
        duration,
        model: this.config.openai302.model,
        messageCount: messages.length
      });

      return response;
    } catch (error) {
      const duration = Date.now() - startTime;
      this.ctx.logger.error('[OpenAI] Request failed', {
        duration,
        error: {
          name: error.name,
          message: error.message,
          code: error.code,
          type: error.type,
          status: error.status
        },
        request: {
          model: this.config.openai302.model,
          messageCount: messages.length
        }
      });

      throw error;
    }
  }
}

module.exports = OpenAIService;
